<form class="layui-form seller-form"  action="" >
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline">
                <select name="year" lay-filter="year" id="year">
                    <option value=''>请选择</option>
                    {volist name="yearList" id="vo"}
                    <option value="{$vo.id}">{$vo.year}</option>
                    {/volist}
                </select>
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label> 
            <div class="layui-input-inline">
                <select name="season" lay-filter="season" id="season">
                    <option value=''>请选择</option>
                    {volist name="seasonList" id="vo1"}
                    <option value="{$vo1.season_id}">{$vo1.season_name}</option>
                    {/volist}
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部/院：</label>
            <div class="layui-input-inline" id="dep_box">
                <select name="dep_id" lay-filter="dep_id" id="dep_id">
                    <option value=''>请选择</option>
                    {volist name="depList" id="vo"}
                    <option value="{$vo.bmdm}">{$vo.bmmc}</option>
                    {/volist}
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">专业：</label>
            <div class="layui-input-inline" id="specialty_box">
                <select name="specialty_id" lay-filter="specialty_id" id="specialty_id" lay-search>
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">班级：</label>
            <div class="layui-input-inline" id="class_box">
                <select name="class_id" lay-filter="class_id" id="class_id" lay-search>
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">学号：</label>
            <div class="layui-input-inline">
                <input id="xh" type="text" name="xh" lay-verify="xh" placeholder="请输入学号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">姓名：</label>
            <div class="layui-input-inline">
                <input id="xm" type="text" name="xm" lay-verify="xm" placeholder="请输入姓名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">退书原因：</label>
            <div class="layui-input-inline">
                <input type="text" name="draw_remark" lay-verify="draw_remark" placeholder="请输入原因" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="search"><i class="iconfont icon-chaxun"></i>筛选</button>

            <button type="button" class="layui-btn layui-btn-sm book-return" id="book-return"><i class="layui-icon">&#xe705;</i> 退书</button>

            <button id="book_return_print" type="button" class="layui-btn layui-btn-sm print"><i class="layui-icon">&#xe66d;</i> 打印</button>
        </div>
    </div>
</form>

<div class="table-body">
	<table id="bookreturn" lay-filter="bookreturn"></table>
</div>

<script>
    layui.use(['table','form','layer','laydate'],function(){
        var layer = layui.layer, table = layui.table,form = layui.form,date = layui.laydate;
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        var printstatus = 1;
        var printindex = 0;
        var myInterval = null;
        var checkedData = new Array(); 
        //执行渲染
        table.render({
            elem: '#bookreturn', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-165',
            cellMinWidth: '80',
            page: 'true',
            limit:'20',
            id:'bookreturn',
            url: "{:url('BookCommon/returnNull')}",
            cols: [[ //标题栏
                {type:'checkbox'},
                {field: 'draw_year', title: '年度',align:'center',width:80},
                {field: 'draw_season', title: '季度',align:'center',width:80},
                {field: 'bmmc', sort: true, title: '部/院',align:'center',width:120},
                {field: 'zymc', sort: true, title: '专业',align:'center',width:120},
                {field: 'bjmc', sort: true, title: '班级',align:'center',width:180},
                {field: 'dirName',sort: true, title: '方向' ,align:'center',width:80},
                {field: 'xh',sort: true, title: '学号' ,align:'center',width:120},
                {field: 'xm',sort: true, title: '姓名' ,align:'center',width:160},
                {field: 'draw_remark', title: '退书原因',align:'center',width:260},
                {field: 'username', sort: true, title: '操作员',align:'center',width:100},
                {
                    field: 'operating', title: '操作', width: 160, align: 'center', templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs" name="bookdetail" id="' + data.id + '"lay-event="bookdetail">教材明细</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" name="del" lay-event="del">删除</a>';
                        return html;
                    }
                },
            ]], //设置表头
            done: function(res, curr, count){
                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            }
        });
 
        
        // 查询
        form.on('submit(search)', function(data){
            var year = data.field.year;
            var season = data.field.season;
            if(!year){
                layer.msg('年度不能为空！', {time: 1300});
                return false;
            }
            if(!season){
                layer.msg('季度不能为空！', {time: 1300});
                return false;
            }
            layui.table.reload('bookreturn', {
                where: data.field,
                page: {curr: 1}, //重新从第 1 页开始
                url: "{:url('BookReturn/index')}",
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        // 联动专业
        layui.use('form', function () {
            form.on('select(dep_id)', function (data) {
                getSpecialty(data);
            });
            
            form.on('select(specialty_id)', function (data) {
                getClass(data);
            });
        });
        
        // 得到专业
        function getSpecialty(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getSpecicalties')}",
                data: 'bmdm=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#specialty_id").empty();//清空下拉框的值
                        $('#specialty_id').append(new Option('', ''));// 下拉菜单里添加元素
                        
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#specialty_id').append(new Option(item.zymc, item.zydm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 得到班级
        function getClass(data) { 
            var dept = $("#dep_id").val();
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getCWClasses')}",
                data: {
                        "bmdm": dept,
                        "zydm": data.value
                    },
                success: function(e) {
                    if(e.status) {
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data, function (index, item) {
                            $('#class_id').append(new Option(item.bjmc, item.bjdm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 监听工具条
        table.on('tool(bookreturn)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if(layEvent === 'bookdetail'){ // 修改
                $("a[name='bookdetail']").addClass("layui-btn-disabled");
                $("a[name='bookdetail']").attr("disabled", true);
                
                JsGet("{:url('BookReturn/bookreturnbookdetail')}?id=" + data.id, function(e){
                    $("a[name='bookdetail']").removeClass("layui-btn-disabled");
                    $("a[name='bookdetail']").removeAttr("disabled");
                    if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                        layer.msg(e.msg); return false;
                    }

                    window.box = layer.open({
                        type: 1,
                        content: e,
                        area: ['750px', '460px'],
                        title: '教材列表'
                    })
                });
            } else if(layEvent === 'del'){ // 修改
               // $("a[name='del']").addClass("layui-btn-disabled");
              //  $("a[name='del']").attr("disabled", true);
                
                layer.confirm('您确定删除此退书记录吗？', {
                    btn: ['确认', '取消'], //按钮
                    cancel:function(index, layero){
                  //      $("a[name='del']").removeClass("layui-btn-disabled");
                 //       $("a[name='del']").removeAttr("disabled");
                    }
                }, function () {
                    JsPost("{:url('BookReturn/bookreturndel')}", {returnId:data.id}, function (res) {
                    //    $("a[name='del']").removeClass("layui-btn-disabled");
                   //     $("a[name='del']").removeAttr("disabled");
                        
                        //删除逻辑中判断只有一条数据时应该刷新前一页信息
                        layer.msg(res.msg);
                        if(res.status){
                            if(dataNum == 1){
                                currPage = currPage - 1;
                            }

                            table.reload('bookreturn', {
                                page: {
                                    curr: currPage
                                }
                            });
                            return false;
                        }
                    });
                }, function () {
                  //  $("a[name='del']").removeClass("layui-btn-disabled");
                  //  $("a[name='del']").removeAttr("disabled");
                    layer.close(1);
                }); 
            }
        });

        //ajax提交退书
        $(document).on('click','.book-return',function(){
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage("{:url('BookReturn/bookReturn')}", '退书'); 
            return false;
        });
 
        function printBookReturnInfo(bookReturnInfo) {
            // 获取打印信息
            JsGet("{:url('BookPlan/getBookReturnInfoByReturnId')}?id="+bookReturnInfo['id'], function (res) {
                if(res.status){
                    // 构造打印数据
                    var ip = '127.0.0.1';
                    var port = '12345';

                    if(ip==""||port==""){ 
                        layer.msg("ip,port不能为空", { time: 1300 }); 
                        return false;
                    }
                    
                    var msg = '{'
                        +'"method":"' + 'printreport' +'"'
                        +',"ReportType":"' + 'gridreport' +'"'  /*报表类型 gridreport fastreport reportmachine 为空 将默认为gridreport  */
                        +',"ReportName":"' + 'studentbookreturn.grf' +'"' /*报表文件名 测试报表 */

                        +',"ReportVersion":"' + '1' +'"' /*可选。报表版本, 为空则默认1  如果本地报表的版本过低 将从 ReportUrl 地址进行下载更新*/
                        +',"ReportUrl":"' + '' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        //+',"ReportUrl":"' + 'http://localhost/test.grf' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        +',"Copies":"' + '1' +'"' /*可选。打印份数，支持指定打印份数。默认1份,如果为零,不打印,只返回报表生成的pdf,jpg等文件*/
                        
                        +',"Duplex":"' + '0' +'"' /*可选。双面打印 默认 0 需要双面打印的时候,请设置 2 或者3 , 可设置 0 打印机默认 1 单页 2 水平 3 垂直*/
                        
                        //+',"PrinterName":"' + $("#PrinterS option:selected").text() +'"' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrinterName":""' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrintOffsetX":"' + '0' +'"' /*可选。打印右偏移，单位厘米。报表的水平方向上的偏移量，向右为正，向左为负。*/
                        +',"PrintOffsetY":"' + '0' +'"' /*可选。打印下偏移，单位厘米。 报表的垂直方向上的偏移量，向下为正，向上为负。*/
                        +',"Preview":"' + '0' +'"'  /*可选。是否预览，和主界面设置的效果一样 为空默认不预览,   0：不预览，1：预览(弹出导出的pdf,jpg等文件)。*/
                        +',"token":"' + 'aa' +'"' /*可选。只要token值在列表中 方可打印*/
                        +',"taskId":"' + '1234567' +'"' /*可选。多个打印任务同时打印时，根据该id确定返回的是哪个打印任务。 */
                        +',"exportfilename":"' + '' +'"'  /*可选。自定义 导出 文件名称 为空 或者 自定义名称 如 test */
                        +',"exportfiletype":"' + '' +'"'  /*可选。自定义 导出 文件格式 为空 或者 自定义名称 如 pdf  */

                        +',"Control": ['  ///*部件框，可选值：AsStaticBox ,AsMemoBox,AsRichTextBox,AsPictureBox (url或base64格式),AsBarcode*/
                                //静态框 AsStaticBox  综合文字框 AsMemoBox, RTF文本框 AsRichTextBox,图像框 AsPictureBox (url或base64格式), 条码二维码 AsBarcode*
                                +'{"type": "AsStaticBox", "name": "xh","value": "'+bookReturnInfo['xh']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "xm","value": "'+bookReturnInfo['xm']+'","required": false},' 
                                +'{"type": "AsStaticBox", "name": "dep","value": "'+bookReturnInfo['bmmc']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "dir","value": "'+bookReturnInfo['dirName']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "class","value": "'+bookReturnInfo['bjmc']+'","required": false},'
                            +']'
                        
                        +',"Field": ['  ///*字段， type ftBlob (base64格式) ,ftString ftInteger ftBoolean, ftFloat, ftCurrency,ftDateTime,  size (ftString 设置为实际长度,其他的设置为0,例如 ftInteger ftBlob 等设置为0 ) 
                                
                                +'{"type": "ftString", "name": "xuhao","size": 255,"required": true},'
                                +'{"type": "ftString", "name": "jiaocai","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "chubanshe","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "ISBN","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "shuliang","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "danjia","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "jine","size": 255,"required": false},' 
                                +'{"type": "ftString", "name": "beizhu","size": 255,"required": false},' 

                            +']'

                        +',"Data": [';  ///*数据行

                            $.each(res.data, function(index, item){
                                msg += '{"xuhao": "'+item['xuhao']+'", "jiaocai": "'+item['jiaocai']+'","chubanshe": "'+item['chubanshe']+'", "ISBN": "'+item['ISBN']+'", "shuliang": "'+item['shuliang']+'", "danjia": "'+item['danjia']+'","jine": "'+item['jine']+'","beizhu": "'+item['beizhu']+'"},'
                            })

                            msg +=']'
                            
                        msg += '}';
                    
                    jQuery.support.cors = true;
                    $.ajax({
                        async : false,
                        url : "http://"+ip+":"+port+"/",
                        type : "POST",
                        contentType: "application/x-www-form-urlencoded", //要这样设置  
                        dataType : "json",
                        crossDomain: true,
                        data : msg,
                        beforeSend: function (XMLHttpRequest) {
                        },
                        success: function(data){	
                            printstatus = 1;	
                            if(data.status=="ok"){
                                layer.msg("打印成功:"+data.data, { time: 1300 }); 
                                // 添加打印日志
                                printLog = {
                                    "func_type": 4
                                    ,"func_id": bookReturnInfo['id']
                                    ,"operator": {$userId}
                                    ,"content": "个人退书"};
                                addPrintLog(printLog);
                            }else{
                                layer.msg("打印失败:"+data.data, { time: 1300 });
                            }
                        },
                        error: function(data){
                            layer.msg("连接HttpPrinter失败:"+JSON.stringify(data), { time: 1300 });
                        }
                    });
                }
            })
        }
        
        // 打印状态检查
        function printTimer() {
            if(printstatus == 1) { 
                printstatus = 0;
                printBookReturnInfo(checkedData[printindex]);
                printindex++;
            }

            if (printindex == checkedData.length) {
                window.clearInterval(myInterval);
                checkedData = new Array();
                myInterval = null;
                printindex = 0;
                printstatus = 1;
            }
        }

        // 打印
        $(document).on('click','.print',function(){
            var checkStatus = table.checkStatus('bookreturn');
            checkedData = checkStatus.data;

            if(checkedData.length==0){
                layer.msg('请先选择要打印的数据行！', { time: 1300 });
                return false;
            }

            $('#book_return_print').addClass("layui-btn-disabled");
            $('#book_return_print').attr("disabled", true);

            myInterval = setInterval(function(){ printTimer() }, 1000);

            $('#book_return_print').removeClass("layui-btn-disabled");
            $('#book_return_print').removeAttr("disabled");
        });
        
       
        $('#year').val({$curr_year});
        layui.form.render("select");//重新渲染 固定写法

        $("#season").val({$curr_season});
        layui.form.render("select");//重新渲染 固定写法

        // 添加打印日志
        function addPrintLog(data){
            JsPost("{:url('BookCommon/addPrintLog')}", data, function (res) {
                if(res.status){
                } else{
                }
                // layer.msg(res.msg);
            });
        }
    })
</script>

